<?php
/**
 * @file : celebrity.php
 * @date : 2014-12-26
 * @author : yuebin
 */
namespace haibao\cms\data;

use haibao\cms\model\filter\Celebrity as CelebrityFilter;
use haibao\cms\model\filter\CelebrityInfo as CelebrityInfoFilter;

class Celebrity extends \haibao\cms\data\BaseMysql{
    
    public function __construct(){
        parent::__construct('\haibao\cms\model\data\Celebrity');
    }
    
    public function UpdateCelebrityTimeById($id){
        $sqlCelebrity = "update Celebrity set UpdateTime=%s where Id=%s";
        $this->query($sqlCelebrity,array(date('Y-m-d H:i:s'),$id));
    }
    
    public function getCelebrityByName($starName){
        $sql = 'select Id,NameCn,NameEn from Celebrity where (NameCn=%s or NameEn like %s) and Status = 1 limit 1';
        return $this->query($sql,array($starName,$starName))->fetch_assoc();
    }

    public function getNewVote($guessId){
    	$newVoteArr = $newVote = array();
    	$sql = 'select Id,VoteNum from ArticleVoteProperty where ArticleVoteId = %s';
    	$result = $this->query($sql,array($guessId));
    	while($row = $result->fetch_assoc()){
    		$newVote['Id'] = $result->getData('Id');
    		$newVote['VoteNum'] = $result->getData('VoteNum');
    		$newVote['VotePer'] = '';
    		$newVoteArr[] = $newVote;
    	}
    	return $newVoteArr;
    }
    
    
    /**
     * 明星库首页  添加明星投票(明星猜猜猜)
     */
    public function addStarVote($id,$guessId,$userId){
    	$sql = 'update ArticleVoteProperty set VoteNum = VoteNum+1 where Id = %s ';
    	$this->query($sql,array($id));
    	$nowTime = new \DateTime();
    	$sqlAddUser = 'insert into ArticleVoteByUser(`CreateBy`,`ArticleVoteId`,`ArticleVotePropertyId`,`CreateTime`) values(%s,%s,%s,%s)';
    	$this->query($sqlAddUser,array($userId,$guessId,$id,$nowTime));
    }
    
    /**
     * 判断是否投过该情侣
     */
    public function checkUserVoteBanPei($userId,$relationId){
    	$sql = 'select * from CelebrityRelationUser where UserId = %s and RelationId = %s limit 1';
    	$result = $this->query($sql,array($userId,$relationId))->fetch_assoc();
    	if($result){
    		$sql = 'select * from CelebrityRelation where Id = %s';
    		return $this->query($sql,array($relationId))->fetch_assoc();
    	}else {
    		return '';
    	}
    }

    /**
     * 明星库首页  添加明星般配数
     */
    public function addStarMached($matchType,$relationTableId,$user){
    	$this->beginTranscation();
	    try {
	    	//更改投票数
	    	if($matchType == 1){//般配
	    		$sql = 'update CelebrityRelation set `Match` = `Match`+1 where Id = %s';
	    	}else {
	    		$sql = 'update CelebrityRelation set `NoMatch` = `NoMatch`+1 where Id = %s';
	    	}
	    	$this->query($sql,array($relationTableId));
	    	
	    	//添加投票用户记录
	    	$nowTime = new \DateTime();
	    	$sqlAddUser = 'insert into CelebrityRelationUser(`RelationId`,`UserId`,`Choice`,`AddTime`) values(%s,%s,%s,%s)';
	    	$this->query($sqlAddUser,array($relationTableId,$user,$matchType,$nowTime));
    	} catch (\Exception $e) {
    		$this->rollback();
    		throw $e;
    	}
    	$this->endTranscation();
    }
    
    /**
     * 获取所有明星总数量
     */
    public function getStarListCount(){
    	$sql = 'select count(*) as starNum from Celebrity where Status = %s';
    	return $this->query($sql,array(\haibao\cms\model\data\Celebrity::STATUS_ENABLE))->fetch_assoc();
    }
    
    public function addCelebrityClickNum($celebrityId){
    	$sql = 'update CelebrityRiseCount set ClickNum=ClickNum+1,EditClickNum=EditClickNum+1 where CelebrityId=%s';
    	$result  = $this->query($sql,array($celebrityId));
    }
    
    /**
     * 通过明星ID获取粉丝数 EditFansNum ,点击量
     */
    public function getStarFansNumByCelebrityId($celebrityId,$type){
    	$result = array();
    	if($type == \haibao\cms\model\data\Brand::TYPE_FANSNUM){
    		$sql = 'select EditFansNum from CelebrityRiseCount where CelebrityId = %s';
    	}else if($type == \haibao\cms\model\data\Brand::TYPE_CLICKNUM){
    		$sql = 'select EditClickNum from CelebrityRiseCount where CelebrityId = %s';
    	}
    	$result = $this->query($sql,array($celebrityId))->fetch_assoc();
    	return $result;
    }
    
    /**
     * 修改粉丝数 EditFansNum ,点击量
	 * @param string $editFansNum
	 * @param string $celebrityId
	 * @param string $type 类型(粉丝数/点击量)
     */
    public function editStarFansNumByCelebrityId($editFansNum,$celebrityId,$type){
    	if($type == \haibao\cms\model\data\Brand::TYPE_FANSNUM){
    		$sql = 'update CelebrityRiseCount set EditFansNum = %s where CelebrityId = %s';
    	}else if($type == \haibao\cms\model\data\Brand::TYPE_CLICKNUM){
    		$sql = 'update CelebrityRiseCount set EditClickNum = %s where CelebrityId = %s';
    	}
    	$this->query($sql,array($editFansNum,$celebrityId));
    }
    
    /**
     * 添加明星
     * @param Object \haibao\cms\model\data\Celebrity $celebrityModel
     */
    public function addCelebrity($celebrityModel,$userName,$addTag = false){

        $this->beginTranscation();
        try{
            if($addTag){
				$this->addTag($celebrityModel);
			}
            $this->add($celebrityModel);
        	
        	$this->addBrandRelStar($celebrityModel);
        	
        	$this->addCelebrityRel($celebrityModel);
        	
        	$this->addCelebrityRiseCount($celebrityModel->Id);

			$starDefineData = new \haibao\cms\data\star\StarDefine();
			if($celebrityModel->StarSecret){
				$celebrityModel->StarSecret->StarId = $celebrityModel->Id;
				$this->add($celebrityModel->StarSecret);
				//$starDefineData->addStarSecret($celebrityModel->Id,$celebrityModel->StarSecret);
			}
			
			
        	$celebrityImageData = new CelebrityImage();
        	// 通过图片修改图片状态
        	$celebrityImageData->updateAllImageStatus($celebrityModel,\haibao\cms\model\data\ImageLibrary::STATUS_ENABLE,$userName);
            // 生成操作LOG
            $this->addEditLog(\haibao\cms\model\data\CelebrityEditLog::TYPE_ADD, $celebrityModel);
        
        } catch(\Exception $e){
        
        	$this->rollback();
        	throw $e;
        
        }
        $this->endTranscation();
    	return $celebrityModel;
    }

	private function addTag($celebrityModel){
		$tagModel = new \haibao\cms\model\data\Tag();
		$tagModel->TagName = $celebrityModel->NameCn;
		$tagModel->TagStatus = \haibao\cms\model\data\Tag::STATUS_ENABLE;
		$tagModel->ParentId = $celebrityModel->ParentTagId;
		$tagModel->TagType = \haibao\cms\model\data\Tag::TYPE_STAR;
		$celebrityModel->TagId = \haibao\cms\business\Tag::addTag($tagModel,true);
	}
    
    /**
     * 其他模块调用添加明星
     */
    public function addCelebrityForOther($celebrityModel,$userName){
    	$this->beginTranscation();
    	try{
    		$this->add($celebrityModel);
    		$this->addCelebrityRiseCount($celebrityModel->Id);
    		// 生成操作LOG
    		$this->addEditLog(\haibao\cms\model\data\CelebrityEditLog::TYPE_ADD, $celebrityModel);
    	
    	} catch(\Exception $e){
    	
    		$this->rollback();
    		throw $e;
    	}
    	$this->endTranscation();
    	return $celebrityModel;
    }

    /**
     * 修改明星
     * @param Object \haibao\cms\model\data\Celebrity $celebrityModel
     */
    public function updateCelebrityById($celebrityModel,$userName,$addTag){
       
        list($celebrityArrSet,$celebrityInfoArrSet) = $this->packageCelebrityFilter($celebrityModel); 

        $celebrityInfoData = new CelebrityInfo();
        $celebrityImageData = new CelebrityImage();
        
        $celebrityInfoFilter = new CelebrityInfoFilter();
        $celebrityInfoFilter->where($celebrityInfoFilter::CONDITION_FIELD_NAME_CELEBRITY_ID,\haibao\frame\data\query\Condition::CONDITION_EQUAL, $celebrityModel->Id);
        
        $this->begintranscation();
        try{
			if($addTag){
				$this->addTag($celebrityModel);
				$celebrityArrSet[CelebrityFilter::CONDITION_FIELD_NAME_TAG_ID] = $celebrityModel->TagId;
			}
            $this->updateById($celebrityModel->Id,$celebrityArrSet);
            $celebrityInfoData->update($celebrityInfoArrSet,$celebrityInfoFilter);

            $celebrityImageData->updateImageByCelebrityId($celebrityModel,$userName);

            $this->addEditLog(\haibao\cms\model\data\CelebrityEditLog::TYPE_UPDATE, $celebrityModel);

            $this->delBrandRelStar($celebrityModel->Id);
            $this->addBrandRelStar($celebrityModel);

			//动态添加的明星未发布不进行关联
			if($celebrityModel->TagId){
				$this->delCelebrityRel($celebrityModel);
				$this->addCelebrityRel($celebrityModel);
			}
			
        } catch (\Exception $e){
            $this->rollback();
        }
        $this->endtranscation();
    }

 
    /**
     * 通过中文名获取明星信息
     * @param Object \haibao\cms\model\data\Celebrity $celebrityModel
     */
    public function checkCelebrityIsExist($celebrityModel){

        $sql = 'select NameCn from `Celebrity` where NameCn=%s and NameEn=%s limit 1';
        $result = $this->query($sql, array($celebrityModel->NameCn,$celebrityModel->NameEn));
        
        while ($result->fetch_assoc()){
            return true;
        }
        return false;
    }
 
    
    /**
     * 获取明星信息
     * @param Object \haibao\cms\model\filter\Celebrity $celebrityFilter
     */
    public function getAll($celebrityFilter){
        return parent::getAll($celebrityFilter);
    }

    /**
     * 根据明星ID获取明星信息
     * @param Int $id 明星ID 
     */
    public function getCelebrityById($id){

        // 后期考虑存入缓存
        return $this->getOneById($id);
    }

    /**
     * 根据标签ID更新明星信息
     * @param : Array $arrSet
     * @param : Object \haibao\cms\model\filter\Celebrity $filter
     * @param : Object \haibao\cms\model\data\Celebrity $model
     */
    public function updateCelebrityByFilter($arrSet,$filter,$model = null){
    
    	$this->beginTranscation();
    	try{
    		$this->update($arrSet,$filter);
    
    	}catch (\Exception $e) {
    		$this->rollback();
    		throw $e;
    	}
    	$this->endTranscation();
    
    	if(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)){
    	}
    }
    /**
     * 删除明星通过tagId
     */
    public function deleteCelebrityByTagId($tagId,$filter){
    	parent::update(array(CelebrityFilter::CONDITION_FIELD_NAME_STATUS=>\haibao\cms\model\data\Celebrity::STATUS_DISABLE), $filter);
    	if(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)){
    		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
    		$sql ="update `library_celebrity` set status =0 where tag_id= %s";
    		$this->query($sql,array($tagId));
    	}
    }
    
    public function getCelebrityForRank($rankConditions){
   		$orderBy = $rankConditions['rankType'] == 2 ? 'FansCount' : 'WeightCount';
   		$andGender = $rankConditions['gender'] ? 'and CB.Gender='.$rankConditions['gender'] : '' ;
   		$andWhere = $rankConditions['starType'] > 0 ? " and instr(CB.StarTypes, '[".$rankConditions['starType']."]') " : '';
    	$sql = "SELECT CB.Id,CB.TagId,CB.NameCn,CB.NameEn,CBR.EditFansNum AS FansCount,CBR.CommentsCount,CBR.WeightCount
    			 FROM Celebrity CB LEFT JOIN CelebrityRiseCount CBR
    			 ON CB.Id = CBR.CelebrityId 
    			WHERE 1 ".$andGender.$andWhere." 
    			ORDER BY CBR.".$orderBy." DESC 
    			LIMIT 100";
    	$result = $this->query($sql);
    	$resData = array();
    	
    	while($result->fetch_assoc()){
    		$tag = $result->getData('Id');
    		$resData[$tag]['Id'] = $tag;
    		$resData[$tag]['TagId'] = $result->getData('TagId');
    		$resData[$tag]['NameCn'] = $result->getData('NameCn');
    		$resData[$tag]['NameEn'] = $result->getData('NameEn');
    		$resData[$tag]['FansCount'] = $result->getData('FansCount');
    		$resData[$tag]['CommentsCount'] = $result->getData('CommentsCount');
    	}
    	return $resData;
    }
    
    public function getAllCelebrityIdByWeight(){
    	$cache = new \haibao\cms\cache\Celebrity();
    	$arrCelebrityId = $cache->getCelebrityCacheData();
    	if(!$arrCelebrityId){
    		$arrCelebrityId = array();
    		$arrCelebrityInfo = array();
    		$arrTagId = array();
	    	$sql = 'select b.Id,b.TagId,s.WeightCount from Celebrity as b left join CelebrityRiseCount as s on b.Id = s.CelebrityId where b.Status=%s order by s.WeightCount desc';
	    	$result = $this->query($sql,array(\haibao\cms\model\data\Celebrity::STATUS_ENABLE));
	    	while ($result->fetch_assoc()){
	    		$arrTagId[] = $result->getData('TagId');
	    		$arrCelebrityInfo[$result->getData('Id')] = $result->getData('TagId');
	    	}
	    	
	    	$data = new \haibao\cms\data\Tag();
	    	$topPicIds = $data->getTopicIdByTagId($arrTagId);
	    	foreach($arrCelebrityInfo as $celebrityId=>$celebrityTagId){
	    		if(isset($topPicIds[$celebrityTagId]) && $topPicIds[$celebrityTagId]){
	    			$arrCelebrityId[] = $celebrityId;
	    		}
	    	}
	    	$cache->setCelebrityCacheData($arrCelebrityId);
    	}
    	return $arrCelebrityId;
    }
    
    public function updateCommentNum($starId,$userId,$num = 1,$isSub=false){
    	if ($isSub){
    		$sql = 'update CelebrityRiseCount set CommentsCount=CommentsCount-'.$num.' where CelebrityId=%s';
    	}else {
    		$sql = 'update CelebrityRiseCount set CommentsCount=CommentsCount+'.$num.' where CelebrityId=%s';
    		
    		$additionalSql = "insert into CelebrityAttentionRecord(CelebrityId,UserId,CreateTime,RecordType) value(%s,%s,%s,%s)";
    		$this->query($additionalSql,array($starId,$userId,date('Y-m-d H:i:s'),\haibao\cms\model\data\CelebrityAttentionRecord::RECORD_TYPE_COMMENT));
    	}
    	$this->query($sql,array($starId));
    }
    
    public function getCelebrityRiseCountById($id){
    	$sql = "select * from CelebrityRiseCount where CelebrityId=%s";
    	return $this->query($sql,array($id))->fetch_assoc();
    }
    /**
     * 封装修改明星参数
     * @param Object \haibao\cms\model\data\Celebrity $celebrityModel
     */
    private function packageCelebrityFilter($celebrityModel){
        $celebrityArr = array(
            CelebrityFilter::CONDITION_FIELD_NAME_NAME_CN => $celebrityModel->NameCn, 
            CelebrityFilter::CONDITION_FIELD_NAME_NAME_EN => $celebrityModel->NameEn, 
            CelebrityFilter::CONDITION_FIELD_NAME_GENDER => $celebrityModel->Gender, 
            CelebrityFilter::CONDITION_FIELD_NAME_PLACE => $celebrityModel->Place, 
        	CelebrityFilter::CONDITION_FIELD_NAME_CATEGORY => $celebrityModel->Category,
            CelebrityFilter::CONDITION_FIELD_NAME_STAR_TYPES => $celebrityModel->StarTypes, 
            CelebrityFilter::CONDITION_FIELD_NAME_BIRTHDAY => $celebrityModel->Birthday, 
            CelebrityFilter::CONDITION_FIELD_NAME_PINYIN_CH => $celebrityModel->PinyinCh, 
            CelebrityFilter::CONDITION_FIELD_NAME_PINYIN_EN => $celebrityModel->PinyinEn, 
            CelebrityFilter::CONDITION_FIELD_NAME_EDITOR => $celebrityModel->Editor, 
            CelebrityFilter::CONDITION_FIELD_NAME_STATUS => $celebrityModel->Status, 
            CelebrityFilter::CONDITION_FIELD_NAME_DESCRIPTION => $celebrityModel->Description, 
            CelebrityFilter::CONDITION_FIELD_NAME_UPDATE_TIME => date('Y-m-d H:i:s'),
            CelebrityFilter::CONDITION_FIELD_NAME_IS_APP_USE => $celebrityModel->IsAppUse,
        );

        $celebrityInfoArr = array(
        
            CelebrityInfoFilter::CONDITION_FIELD_NAME_MORE_CH_NAME => $celebrityModel->CelebrityInfo->MoreChName,
            CelebrityInfoFilter::CONDITION_FIELD_NAME_MORE_EH_NAME => $celebrityModel->CelebrityInfo->MoreEnName,
            CelebrityInfoFilter::CONDITION_FIELD_NAME_DIE_DATE => $celebrityModel->CelebrityInfo->DieDate,
            CelebrityInfoFilter::CONDITION_FIELD_NAME_XING_ZUO => $celebrityModel->CelebrityInfo->XingZuo,
            CelebrityInfoFilter::CONDITION_FIELD_NAME_BIRTH_PLACE => $celebrityModel->CelebrityInfo->BirthPlace,
            CelebrityInfoFilter::CONDITION_FIELD_NAME_HEIGHT => $celebrityModel->CelebrityInfo->Height,
            CelebrityInfoFilter::CONDITION_FIELD_NAME_BLOOD => $celebrityModel->CelebrityInfo->Blood,
            CelebrityInfoFilter::CONDITION_FIELD_NAME_SCHOOL => $celebrityModel->CelebrityInfo->School,
            CelebrityInfoFilter::CONDITION_FIELD_NAME_EC_COMPANY => $celebrityModel->CelebrityInfo->EcCompany,
            CelebrityInfoFilter::CONDITION_FIELD_NAME_REP_WORKS => $celebrityModel->CelebrityInfo->RepWorks,
            CelebrityInfoFilter::CONDITION_FIELD_NAME_SUCCESS => $celebrityModel->CelebrityInfo->Success,
            CelebrityInfoFilter::CONDITION_FIELD_NAME_FAMILY => $celebrityModel->CelebrityInfo->Family,
            CelebrityInfoFilter::CONDITION_FIELD_NAME_INSTAGRAM_URL => $celebrityModel->CelebrityInfo->InstagramUrl,
            CelebrityInfoFilter::CONDITION_FIELD_NAME_BLOG_URL => $celebrityModel->CelebrityInfo->BlogUrl,
            CelebrityInfoFilter::CONDITION_FIELD_NAME_MIRCO_URL => $celebrityModel->CelebrityInfo->MircoBlog,
            CelebrityInfoFilter::CONDITION_FIELD_NAME_OFFICE_WEB => $celebrityModel->CelebrityInfo->OfficeWeb,
            CelebrityInfoFilter::CONDITION_FIELD_NAME_LOOKBOOK => $celebrityModel->CelebrityInfo->Lookbook,
            CelebrityInfoFilter::CONDITION_FIELD_NAME_FACEBOOK => $celebrityModel->CelebrityInfo->Facebook,
            CelebrityInfoFilter::CONDITION_FIELD_NAME_TWITTER => $celebrityModel->CelebrityInfo->Twitter,
            CelebrityInfoFilter::CONDITION_FIELD_NAME_COUNTRY => $celebrityModel->CelebrityInfo->Country,
        );
        /*
        $celebrityImageArr = array();
        foreach($celebrityModel->CelebrityImage as $image){
        	
        	$celebrityImageArr[CelebrityImageFilter::CONDITION_FIELD_NAME_IMAGE_ID] = $image->ImageId;
        	
        }
        $celebrityImageArr = array(
        	CelebrityImageFilter::CONDITION_FIELD_NAME_IMAGE_ID => $celebrityModel->CelebrityImage->ImageId
        );
        */
        return array($celebrityArr, $celebrityInfoArr);
    }

    /**
     * 添加明星品牌关联信息
     * @param Object \haibao\cms\model\data\Celebrity $celebrityModel
     */
    private function addBrandRelStar($celebrityModel){

        
        if(!empty($celebrityModel->CelebrityRelBrand)){

            $sql = 'insert into `BrandRelStar` (CelebrityId,BrandId,CooperateTime) values ';

            $sqlArr = $valArr = array();
            foreach($celebrityModel->CelebrityRelBrand as $key=>$arr){

                array_push($sqlArr,'(%s,%s,%s)');
                array_push($valArr,$celebrityModel->Id,$arr['id'],$arr['time']);
            }
            $sql .= implode(',',$sqlArr);
            $this->query($sql,$valArr);
        }
    }
    
    /**
     * 添加明星与明星关联信息
     * @param Object \haibao\cms\model\data\Celebrity $celebrityModel
     */
    private function addCelebrityRel($celebrityModel){
    	
	
    	
        if(!empty($celebrityModel->CelebrityRelStar)){

            $topicId = \haibao\cms\business\Tag::getTopicIdByTagId(array($celebrityModel->TagId));
            foreach($celebrityModel->CelebrityRelStar as $key=>$arr){
            	
            	
            	$sql = 'insert into `CelebrityRelation` (MastarCelebrity,JoinCelebrity,RelationTypeId) values (%s,%s,%s)';
            	$sqlArr = $valArr = array();
                array_push($valArr,$topicId[$celebrityModel->TagId],$arr['id'],$arr['type']);
                $this->query($sql,$valArr);
               	$celebrityModel->CelebrityRelStar[$key]['newId'] = $this->getDb()->insert_id."\n";
            }
            //$sql .= implode(',',$sqlArr);
            //$this->query($sql,$valArr);
        }
    }
    
    /**
     * 删除明星品牌关联信息
     * @param : Int $celebrityId 明星ID
     */
    private function delBrandRelStar($celebrityId){
    
    	$sql = 'delete from `BrandRelStar` where CelebrityId = %s';
    	$this->query($sql,array($celebrityId));
    }
    
    /**
     * 删除明星关联明星信息
     * @param Object \haibao\cms\model\data\Celebrity $celebrityModel
     */
    private function delCelebrityRel($celebrityModel){

    	$topicId = \haibao\cms\business\Tag::getTopicIdByTagId(array($celebrityModel->TagId));

    	$sql = 'delete from `CelebrityRelation` where MastarCelebrity = %s';
    	$this->query($sql,array($topicId[$celebrityModel->TagId]));
    }
    
    /**
     * 添加明星操作LOG
     * @param Int $type 操作类型
     * @param Object \haibao\cms\model\data\Celebrity $celebrityModel
     */
    private function addEditLog($type, $celebrityModel){

        $model = new \haibao\cms\model\data\CelebrityEditLog();
        $model->CelebrityId = $celebrityModel->Id;
        $model->UserId = $celebrityModel->Editor;
        $model->Type = $type;
        $model->EditTime = date('Y-m-d H:i:s');
        $this->add($model);
    }
    
    /**
     * 根据标签ID获取明星信息
     * @param : Array or Int $tagId
     */
    public function getCelebrityByTagId($tagId){
    	
    	$celebrityFilter = new CelebrityFilter();
    	$celebrityFilter->select(array(
    			CelebrityFilter::CONDITION_FIELD_NAME_ID,
    		CelebrityFilter::CONDITION_FIELD_NAME_TAG_ID,
    		CelebrityFilter::CONDITION_FIELD_NAME_NAME_CN,
    		CelebrityFilter::CONDITION_FIELD_NAME_NAME_EN,
    	));

        if(is_array($tagId)){
    		$celebrityFilter->where(CelebrityFilter::CONDITION_FIELD_NAME_TAG_ID,\haibao\frame\data\query\Condition::CONDITION_IN,$tagId);

    	}else{
    		$celebrityFilter->where(CelebrityFilter::CONDITION_FIELD_NAME_TAG_ID,\haibao\frame\data\query\Condition::CONDITION_EQUAL,$tagId);
    	}
    	return $this->getAll($celebrityFilter);
    }
    
    /**
     * 根据明星ID删除明星
     */
    public function deleteCelebrityById($celebrityId, $status = \haibao\cms\model\data\Celebrity::STATUS_DISABLE){
    	try {
    		$this->updateById($celebrityId,array('Status'=>$status));
    	}catch (\Exception $e){
    		throw $e;
    	}
    }
    

    /**
     * 添加旧库明星
     * @param Object \haibao\cms\model\data\Celebrity $celebrityModel
     */
    private function addLibraryCelebrity($model,$userName){
    	$field = '`tag_id`,`desc`,`name_ch`,`name_en`,`gender`,`place`,`startypes`,`birthday`,`pinyin_ch`,`pinyin_en`,`status`,`date`,`tag_type`,`more_ch`,`more_en`,`die_date`,`xingzuo`,`birth_place`,`height`,`blood`,`school`,`ec_company`,`rp_works`,`success`,`family`,`editor`';
    
    	$arrSql = $arrValues = array();
    	//array_push($arrSql, '(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)');
    	array_push($arrValues, $model->TagId);
    	array_push($arrValues, $model->Description);
    	array_push($arrValues, $model->NameCn);
    	array_push($arrValues, $model->NameEn);
    	array_push($arrValues, $model->Gender);
    	array_push($arrValues, $model->Place);
    	array_push($arrValues, $model->StarTypes);
    	array_push($arrValues, $model->Birthday);
    	array_push($arrValues, $model->PinyinCh);
    	array_push($arrValues, $model->PinyinEn);
    	if($model->Status == 0){
    		$status = 2;
    	}else{
    		$status = 1;
    	}
    	array_push($arrValues, $status);
    	array_push($arrValues, date('Y-m-d H:i:s'));
    	array_push($arrValues, $model->TagType);

    	array_push($arrValues, $model->CelebrityInfo->MoreChName);
    	array_push($arrValues, $model->CelebrityInfo->MoreEnName);
    	array_push($arrValues, $model->CelebrityInfo->DieDate);
    	array_push($arrValues, $model->CelebrityInfo->XingZuo);
    	array_push($arrValues, $model->CelebrityInfo->BirthPlace);
    	array_push($arrValues, $model->CelebrityInfo->Height);
    	array_push($arrValues, $model->CelebrityInfo->Blood);
    	array_push($arrValues, $model->CelebrityInfo->School);
    	array_push($arrValues, $model->CelebrityInfo->EcCompany);
    	array_push($arrValues, strip_tags($model->CelebrityInfo->RepWorks));
    	array_push($arrValues, strip_tags($model->CelebrityInfo->Success));
    	array_push($arrValues, strip_tags($model->CelebrityInfo->Family));
    	array_push($arrValues, $userName);
    
    	if($model->CelebrityImage){
    		$field .= ',`avatar`,`avatar_640`,`avatar_710`';
	    	// 处理图片
	    	$imageIds = array();
	    	foreach($model->CelebrityImage as $image){
	    		$imageIds[] = $image->ImageId;
	    	}
	    	$images = \haibao\cms\business\ImageLibrary::getImagesById($imageIds);
	    	$imgArr = array();
	    	foreach($images as $img){
	    		$imgArr[$img->Id] = $img->Filename;
	    	}
	    	array_push($arrValues, ltrim($imgArr[$model->CelebrityImage[\haibao\cms\model\data\CelebrityImage::IMAGE_TYPE_PICTURE]->ImageId],'/'));
	    	array_push($arrValues, ltrim($imgArr[$model->CelebrityImage[\haibao\cms\model\data\CelebrityImage::IMAGE_TYPE_SCREEN]->ImageId],'/'));
	    	if(array_key_exists(\haibao\cms\model\data\CelebrityImage::IMAGE_TYPE_OTHER, $model->CelebrityImage)){
	    		array_push($arrValues, ltrim($imgArr[$model->CelebrityImage[\haibao\cms\model\data\CelebrityImage::IMAGE_TYPE_OTHER]->ImageId],'/'));
	    	}else{
	    		array_push($arrValues,null);
	    	}
    	}
    	
    	$arrSql = array_pad($arrSql,count($arrValues),'%s');
    	$sql = 'insert into `library_celebrity` ('.$field.') values ';
    	$sql .=  '(' . implode(',',$arrSql) . ')';
    	$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
    	$this->query($sql, $arrValues);
    	
    	$oldTableCelebrityId = $this->getDb()->insert_id;
    	
    	// 添加明星和品牌的关联关系
    	if(!empty($model->CelebrityRelBrand)){
    		$sqlArr = $valArr = array();
    		$sql = 'insert into `brand_rel_star` (new_star_id,brand_id,date) values ';
    		foreach($model->CelebrityRelBrand as $key=>$arr){
    			array_push($sqlArr,'(%s,%s,%s)');
    			array_push($valArr,$oldTableCelebrityId,$arr['id'],$arr['time']);
    		}
    		$sql .= implode(',',$sqlArr);
    		$this->query($sql,$valArr);
    		/*
    		$brandIdArr = array();
    		foreach($model->CelebrityRelBrand as $key=>$arr){
    		
    			array_push($brandIdArr,$arr['id']);
    		}
    		
    		// DOTO : 获取品牌的信息
    		$brandData = new \haibao\cms\data\Brand();
    		$brands = $brandData->getBrandById($brandIdArr);

    		$sqlArr = $valArr = array();
    		if($brands){
				
    			$sql = 'insert into `library_brand_star_extend` (brandid,starid,tag_desc,tag_story) values ';
    			foreach($brands as $brand){
    				array_push($sqlArr,'(%s,%s,%s,%s)');
    				array_push($valArr,$brand->Id,$model->Id,$brand->Description,$brand->Story);
    			}
    		}
    		$sql .= implode(',',$sqlArr);
    		$this->query($sql,$valArr);
    		*/
    	}
    	
    	// 添加明星与明星的关联关系
    	if(!empty($model->CelebrityRelStar)){
    		 
    		$topicId = \haibao\cms\business\Tag::getTopicIdByTagId(array($model->TagId));
    	
    		foreach($model->CelebrityRelStar as $key=>$arr){
    			$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
    			$sqlArr = $valArr = array();
    			$sql = 'insert into `star_rel` (star_1,star_2,type,status) values (%s,%s,%s,%s)';
    			array_push($valArr,$topicId[$model->TagId],$arr['id'],$arr['type'],1);
    			$this->query($sql,$valArr);
    			$oldId = $this->getDb()->insert_id;
    			$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_CMS );
    			$sql = "insert into DataMigrationMap (TableName,PrimaryKey,OldPrimaryKey) ";
    			$sql .= "values('CelebrityRelation',".$arr['newId'].",".$oldId.")";
    			$this->query($sql);
    		}
    	}
    		
    	$celebrityOldId = $this->getDb()->insert_id;
    
    	//添加新老数据对应表DataMigrationMap
    	$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_CMS );
    	$sql = "insert into DataMigrationMap (TableName,PrimaryKey,OldPrimaryKey) ";
    	$sql .= "values('".$model->getTableName()."',".$model->Id.",".$celebrityOldId.")";
    	$this->query($sql);
    }
    
    /**
     * 修改旧库明星
     * @param Object \haibao\cms\model\data\Celebrity $celebrityModel
     */
    private function updateLibraryCelebrity($model){
        $sql = 'update `library_celebrity` set `desc`=%s,`name_ch`=%s,`name_en`=%s,`gender`=%s,`place`=%s,`startypes`=%s,`birthday`=%s,`pinyin_ch`=%s,`pinyin_en`=%s,`status`=%s,`date`=%s,`more_ch`=%s,`more_en`=%s,`die_date`=%s,`xingzuo`=%s,`birth_place`=%s,`height`=%s,`blood`=%s,`school`=%s,`ec_company`=%s,`rp_works`=%s,`success`=%s,`family`=%s ,`update`=%s ,`avatar`=%s,`avatar_640`=%s,`avatar_710`=%s where tag_id=%s';
    	$arrValues = array();
    	array_push($arrValues, $model->Description);
    	array_push($arrValues, $model->NameCn);
    	array_push($arrValues, $model->NameEn);
    	array_push($arrValues, $model->Gender);
    	array_push($arrValues, $model->Place);
    
    	array_push($arrValues, $model->StarTypes);
    	array_push($arrValues, $model->Birthday);
    	array_push($arrValues, $model->PinyinCh);
    	array_push($arrValues, $model->PinyinEn);
    	if($model->Status == 0){
    		$status = 2;
    	}else{
    		$status = 1;
    	}
    	array_push($arrValues, $status);
    	array_push($arrValues, date('Y-m-d H:i:s'));
    	array_push($arrValues, $model->CelebrityInfo->MoreChName);
    	array_push($arrValues, $model->CelebrityInfo->MoreEnName);
    	array_push($arrValues, $model->CelebrityInfo->DieDate);
    	array_push($arrValues, $model->CelebrityInfo->XingZuo);
    	array_push($arrValues, $model->CelebrityInfo->BirthPlace);
    	array_push($arrValues, $model->CelebrityInfo->Height);
    	array_push($arrValues, $model->CelebrityInfo->Blood);
    	array_push($arrValues, $model->CelebrityInfo->School);
    	array_push($arrValues, $model->CelebrityInfo->EcCompany);
    	array_push($arrValues, strip_tags($model->CelebrityInfo->RepWorks));
    	array_push($arrValues, strip_tags($model->CelebrityInfo->Success));
    	array_push($arrValues, strip_tags($model->CelebrityInfo->Family));
    	array_push($arrValues, date('Y-m-d H:i:s'));
    	
    	// 处理图片
    	$imageIds = array();
    	foreach($model->CelebrityImage as $image){
    		$imageIds[$image->ImageType] = $image->ImageId;
    	}
    	$images = \haibao\cms\business\ImageLibrary::getImagesById($imageIds);
    	$imgArr = array();
    	foreach($images as $img){
    		$imgArr[$img->Id] = $img->Filename;
    	}
    	if($model->CelebrityImage[\haibao\cms\model\data\CelebrityImage::IMAGE_TYPE_PICTURE]->ImageId){
    		array_push($arrValues, ltrim($imgArr[$model->CelebrityImage[\haibao\cms\model\data\CelebrityImage::IMAGE_TYPE_PICTURE]->ImageId],'/'));
    	}else{
    		array_push($arrValues,"");
    	}
    	if($model->CelebrityImage[\haibao\cms\model\data\CelebrityImage::IMAGE_TYPE_SCREEN]->ImageId){
    		array_push($arrValues, ltrim($imgArr[$model->CelebrityImage[\haibao\cms\model\data\CelebrityImage::IMAGE_TYPE_SCREEN]->ImageId],'/'));
    	}else{
    		array_push($arrValues,"");
    	}
    	if(array_key_exists(\haibao\cms\model\data\CelebrityImage::IMAGE_TYPE_OTHER, $model->CelebrityImage)){
    		if($model->CelebrityImage[\haibao\cms\model\data\CelebrityImage::IMAGE_TYPE_OTHER]->ImageId){
    			array_push($arrValues, ltrim($imgArr[$model->CelebrityImage[\haibao\cms\model\data\CelebrityImage::IMAGE_TYPE_OTHER]->ImageId],'/'));
    		}else{
    			array_push($arrValues,"");
    		}
    	}else{
    		array_push($arrValues,null);
    	}
    	
    	array_push($arrValues, $this->getOneById($model->Id)->TagId);
    	$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
    	$this->query($sql, $arrValues);

    	// 修改老表的明星与品牌的关联关系
    	$sql = 'select id from `library_celebrity` where tag_id=%s limit 1';
    	$result = $this->query($sql,array($model->TagId));
    	while($result->fetch_assoc()){
    		 
    		$oldTableCelebrityId = $result->getData('id');
        }
        if(isset($oldTableCelebrityId)){
            $sql = 'delete from `brand_rel_star` where new_star_id=%s';
            $this->query($sql,array($oldTableCelebrityId));
            if(!empty($model->CelebrityRelBrand)){

                $sqlArr = $valArr = array();
                $sql = 'insert into `brand_rel_star` (new_star_id,brand_id,date) values ';
                foreach($model->CelebrityRelBrand as $key=>$arr){
                    array_push($sqlArr,'(%s,%s,%s)');
                    array_push($valArr,$oldTableCelebrityId,$arr['id'],$arr['time']);
                }
                $sql .= implode(',',$sqlArr);
                $this->query($sql,$valArr);
            /*
            $brandIdArr = array();
            foreach($model->CelebrityRelBrand as $key=>$arr){

                array_push($brandIdArr,$arr['id']);
            }

            // 获取品牌的信息
            $brandData = new \haibao\cms\data\Brand();
            $brands = $brandData->getBrandById($brandIdArr);

            $sqlArr = $valArr = array();
            if($brands){
                $sql = 'insert into `library_brand_star_extend` (brandid,starid,tag_desc,tag_story) values ';
                foreach($brands as $brand){
                    array_push($sqlArr,'(%s,%s,%s,%s)');
                    array_push($valArr,$brand->Id,$model->Id,$brand->Description,$brand->Story);
                }
            }
            $sql .= implode(',',$sqlArr);
            $this->query($sql,$valArr);
             */
            }
        }
        // 修改明星与明星的关联关系
		if($model->TagId){
			$topicId = \haibao\cms\business\Tag::getTopicIdByTagId(array($model->TagId));
			$sql = 'delete from `star_rel` where star_1 = %s';
			$this->query($sql,array($topicId[$model->TagId]));
			if(!empty($model->CelebrityRelStar)){

				$sql = 'insert into `star_rel` (star_1,star_2,type,status) values ';

				$sqlArr = $valArr = array();
				foreach($model->CelebrityRelStar as $key=>$arr){

					$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
					$sqlArr = $valArr = array();
					$sql = 'insert into `star_rel` (star_1,star_2,type,status) values (%s,%s,%s,%s)';
					array_push($valArr,$topicId[$model->TagId],$arr['id'],$arr['type'],1);
					$this->query($sql,$valArr);
					$oldId = $this->getDb()->insert_id;
					$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_CMS );
					$sql = "insert into DataMigrationMap (TableName,PrimaryKey,OldPrimaryKey) ";
					$sql .= "values('CelebrityRelation',".$arr['newId'].",".$oldId.")";
					$this->query($sql);
				}
			}
		}
    }

    public function getCelebrityByIds($celebrityIdsArr){
         
        $celebrityFilter = new CelebrityFilter();
        $celebrityFilter->select(array(
            CelebrityFilter::CONDITION_FIELD_NAME_ID,
            CelebrityFilter::CONDITION_FIELD_NAME_TAG_ID,
            CelebrityFilter::CONDITION_FIELD_NAME_NAME_CN,
            CelebrityFilter::CONDITION_FIELD_NAME_NAME_EN
        ));
    
        $celebrityFilter->where(CelebrityFilter::CONDITION_FIELD_NAME_ID,\haibao\frame\data\query\Condition::CONDITION_IN,$celebrityIdsArr);
    
        return $this->getAll($celebrityFilter);
    }

    public function getCelebrityProperty($celebrityId){
    	$celebrityId = (array)$celebrityId;
    	$celebrityPropertyArr = array();
    	$celebrityStr = preg_replace('/\d+/', '%s', implode(',',$celebrityId));
    	$result = $this->query("select CelebrityId,EditFansNum,ClickNum,EditClickNum from CelebrityRiseCount where CelebrityId in ($celebrityStr)", $celebrityId);
    	while ($result->fetch_assoc()){
    		$temp = array();
    		$temp['FansCount'] = $result->getData('EditFansNum');
    		$temp['ClickNum'] = $result->getData('ClickNum');
    		$temp['EditClickNum'] = $result->getData('EditClickNum');
    		$celebrityPropertyArr[$result->getData('CelebrityId')] = $temp;
    	}
    	return $celebrityPropertyArr;
    }
    
    public function getTvInfoByTagId($tagId){
    	$this->setConfig('haibao_article');
    	$stepOne = 'select tag_id from hmeiju_tag where tag_id_old = %s';
    	$stepTwo = 'select pic_id from hmeiju_article_pic_tags where articleclass_id = %s';
    	$strThree = $strFour = '';
    	$getTagId = $this->query($stepOne,array($tagId))->fetch_assoc();
    	if(!$getTagId){
    		return array();
    	}
    	$getPicIds = $this->query($stepTwo,array($getTagId['tag_id']));
    	$picIds = $objIds = $documents = $disrelPic = array();
    	while ($getPicIds->fetch_assoc()){
    		$picIds[] = $getPicIds->getData('pic_id');
    	}
    	if(!$picIds){
    		return array();
    	}
    	$strThree = preg_replace('/\d+/', '%s', implode(',',$picIds));
    	$stepThree = 'select distinct(obj_id) from hmeiju_article_pic_index where pic_id in ('.$strThree.')';
    	$getObjs = $this->query($stepThree,$picIds);
    	while ($getObjs->fetch_assoc()){
    		$objIds[] = $getObjs->getData('obj_id');
    	}
    	if(!$objIds){
    		return array();
    	}
    	$strFour = preg_replace('/\d+/', '%s', implode(',',$objIds));
    	
    	$stepFour = 'select document_id,title,digest,date,doc_type,property from hmeiju_doc_index where published=1 and status=0 and document_id in ('.$strFour.') order by date desc limit 5';
    	$getDocuments = $this->query($stepFour,$objIds);
    	$tag = 0;
    	$tvHost = \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_TV_HOST);
    	while ($getDocuments->fetch_assoc()){
    		$documents[$tag]['InfoId'] = $getDocuments->getData('document_id');
    		$documents[$tag]['Title'] = $getDocuments->getData('title');
    		$documents[$tag]['Digest'] = $getDocuments->getData('digest');
    		$documents[$tag]['Date'] = $getDocuments->getData('date');
    		$documents[$tag]['Property'] = $getDocuments->getData('property');
    		$documents[$tag]['InfoUrl'] = $getDocuments->getData('doc_type') == 4 ? $tvHost.'article/'.$documents[$tag]['InfoId'].'.htm':$tvHost.'image/'.$documents[$tag]['InfoId'].'.htm';
    		$tag++;
    	}
    	
    	$disrelSql = 'select obj_id,filename from hmeiju_article_pic_index where status = 1 and obj_id in ('.$strFour.') group by obj_id order by disrel desc';
    	$getDisrel = $this->query($disrelSql,$objIds);
    	while ($getDisrel->fetch_assoc()){
    		$disrelPic[$getDisrel->getData('obj_id')] = $getDisrel->getData('filename'); 
    	}
    	foreach ($documents as $key=>$list){
    		$documents[$key]['Image'] = $disrelPic[$list['InfoId']];
    	}
    	if($documents){
    		return array($tvHost.'tag/'.$getTagId['tag_id'].'/',$documents);
    	}else{
    		return array();
    	}
    }
    
    public function getTagIdByCelebrityId($celebrityId){
    	$celebrityFilter = new CelebrityFilter();
    	$celebrityFilter->select(array(
    			CelebrityFilter::CONDITION_FIELD_NAME_ID,
    			CelebrityFilter::CONDITION_FIELD_NAME_TAG_ID,
    	));
    	if(is_array($celebrityId)){
    		$celebrityFilter->where(CelebrityFilter::CONDITION_FIELD_NAME_ID,\haibao\frame\data\query\Condition::CONDITION_IN,$celebrityId);
    	
    	}else{
    		$celebrityFilter->where(CelebrityFilter::CONDITION_FIELD_NAME_TAG_ID,\haibao\frame\data\query\Condition::CONDITION_EQUAL,$celebrityId);
    	}
    	$celebrityTagIds =  $this->getAll($celebrityFilter);
    	$resArr = array();
    	foreach ($celebrityTagIds as $tagId){
    		$resArr[$tagId->Id] = $tagId->TagId;
    	}
    	return $resArr;
    }
    
    private function addCelebrityRiseCount($celebrityId){
        $sql = 'insert into CelebrityRiseCount(`CelebrityId`) values(%s)';
        $this->query($sql,array($celebrityId));
    }
    
    public function getHotPicArticles($tagId,$hotTags){
    	$hotTagStr = preg_replace('/\d+/', '%s', implode(',',$hotTags));
    	$sql = "SELECT * FROM (SELECT
					a3.TagId,a2.Id,a2.Title,a2.PublishTime,a2.PublishId,a3.ParentId
				FROM
					InformationStar a1
				LEFT JOIN Article a2 ON a1.InfoId = a2.Id
				LEFT JOIN ArticleTag a3 ON a3.ArticleId = a1.InfoId
				WHERE
					a1.StarTagId = ".$tagId." AND a2.Status = 0 AND a2.Published = 1 AND a2.`Level` >= 2
				AND a3.TagId IN (".$hotTagStr.") ORDER BY a2.PublishTime DESC ) zz GROUP BY zz.TagId";
    	$result = $this->query($sql,$hotTags);
    	$resArr = array();
    	while ($result->fetch_assoc()){
    		$resArr[$result->getData('TagId')]['ArticleId'] = $result->getData('Id');
    		$resArr[$result->getData('TagId')]['Title'] = $result->getData('Title');
    		$resArr[$result->getData('TagId')]['PublishTime'] = $result->getData('PublishTime');
    		$resArr[$result->getData('TagId')]['PublishId'] = $result->getData('PublishId');
    		$resArr[$result->getData('TagId')]['ParentId'] = $result->getData('ParentId');
    	}
    	return $resArr;
    }
    
    public function getHotPicImageColl($tagId,$hotTags){
    	$hotTagStr = preg_replace('/\d+/', '%s', implode(',',$hotTags));
    	$sql = "SELECT * FROM (SELECT
					DISTINCT a3.TagId,a2.Id,a2.Title,a2.PublishTime,a3.ParentId
				FROM
					InformationStar a1
				LEFT JOIN ImageCollective a2 ON a1.InfoId = a2.Id
				LEFT JOIN ImageCollectiveTag a3 ON a3.ImageCollectiveId = a1.InfoId
				WHERE
					a1.StarTagId = ".$tagId." AND a2.Status = 1 AND a2.Published = 1 AND a2.`Level` >= 2
				AND a3.TagId IN (".$hotTagStr.") ORDER BY a2.PublishTime DESC) zz GROUP BY zz.TagId";
    	$result = $this->query($sql,$hotTags);
    	$resArr = array();
    	while ($result->fetch_assoc()){
    		$resArr[$result->getData('TagId')]['ImageCollId'] = $result->getData('Id');
    		$resArr[$result->getData('TagId')]['Title'] = $result->getData('Title');
    		$resArr[$result->getData('TagId')]['PublishTime'] = $result->getData('PublishTime');
    		$resArr[$result->getData('TagId')]['ParentId'] = $result->getData('ParentId');
    	}
    	return $resArr;
    }
    
    public function getOneNewImage($tagId,$notInArticleIds,$notInImageCollIds){
    	$resArr = $infoData = array();
    	$whereA = $whereI = '';
    	if($notInArticleIds){
    		$whereA = " AND a1.InfoId NOT IN (".preg_replace('/\d+/', '%s', implode(',',$notInArticleIds)).") ";
    	}
    	if($notInImageCollIds){
    		$whereI = " AND a1.InfoId NOT IN (".preg_replace('/\d+/', '%s', implode(',',$notInImageCollIds)).") ";
    	}
    	$articleSql = "SELECT a1.InfoType,a3.TagId,	a2.Id,a2.Title,	a2.PublishTime,	a2.PublishId,a3.ParentId
						FROM
							InformationStar a1
						LEFT JOIN Article a2 ON a1.InfoId = a2.Id
						LEFT JOIN ArticleTag a3 ON a3.ArticleId = a1.InfoId
						WHERE
							a1.StarTagId = ".$tagId."
						AND a2. STATUS = 0
						AND a2.Published = 1
						AND a2.`Level` >= 2".$whereA."
						ORDER BY
							a2.PublishTime DESC LIMIT 1";
    	$imageCollSql = "SELECT
					a1.InfoType,a3.TagId,a2.Id,a2.Title,a2.PublishTime,a3.ParentId
				FROM
					InformationStar a1
				LEFT JOIN ImageCollective a2 ON a1.InfoId = a2.Id
				LEFT JOIN ImageCollectiveTag a3 ON a3.ImageCollectiveId = a1.InfoId
				WHERE
					a1.StarTagId = ".$tagId." AND a2.Status = 1 AND a2.Published = 1 AND a2.`Level` >= 2 ".$whereI."
				 ORDER BY a2.PublishTime DESC LIMIT 1";
    	$resArr = $this->query($imageCollSql,$notInImageCollIds)->fetch_assoc();
    	if($resArr){
    		return $resArr;
    	}else{
    		$resArr = $this->query($articleSql,$notInArticleIds)->fetch_assoc();
    		if($resArr){
    			return $resArr;
    		}else{
    			return $resArr;
    		}
    	}
    }
    
    public function getLibraryStarRecommend(){
        $sql = 'SELECT
                	StarTagId
                FROM
                	(
                		SELECT
                			StarTagId,
                			PublishTime
                		FROM
                			InformationStar
                		WHERE
                			IsPrimaiy = 1
                		ORDER BY
                			PublishTime DESC
                		LIMIT 20
                	) AS c
                GROUP BY
                	c.StarTagId
                ORDER BY
                	PublishTime DESC
                LIMIT 12';
        $starResult = $this->query($sql);
        $starIdArr = array();
        while($row = $starResult->fetch_assoc()){
            $starIdArr[] = $row['StarTagId'];
        }
        return $starIdArr;
    }

    public function getCelebrityIdsFromApp($orderByName = 'HotPoints',$orderBy = 'DESC',$limit = 1){
        $celebrityIds = array();
        $sql = "SELECT Id from Celebrity WHERE IsAppUse=1 AND Status=1 ORDER BY ".$orderByName." ".$orderBy." Limit ".$limit;
        $result = $this->query($sql);
        while($result->fetch_assoc()){
            array_push($celebrityIds, $result->getData('Id'));
        }
        return $celebrityIds;
    }
}
